// 工具函数: 计算两个日期之间的年份和月份差
export const CalculateYearsAndMonths = (startDate, endDate) => {
    const start = new Date(startDate);
    const end = new Date(endDate);
    const years = end.getFullYear() - start.getFullYear();
    const months = end.getMonth() - start.getMonth();
   
    return { years, months };
}

// 工具函数: 通过 年/月 计算 开始时间/结束时间
export const  GetMonthDates = (years, months) => {
    debugger;
     var nowTime = new Date();
     var nowTimeS = nowTime.getTime();
     var preTime = years * 365 * 24 * 60 * 60 * 1000 + months * 30 * 24 * 60 * 60 * 1000;
     var endDate = nowTime.getFullYear() + "-" + (nowTime.getMonth()+1 < 10 ? "0" + (nowTime.getMonth()+1) : nowTime.getMonth()+1) + "-" + (nowTime.getDate() < 10 ? "0"+nowTime.getDate() : nowTime.getDate());
     var oldTime = new Date(nowTimeS - preTime);
     var startDate = oldTime.getFullYear() + "-" + (oldTime.getMonth()+1 < 10 ? "0"+(oldTime.getMonth()+1) : oldTime.getMonth()+1) + "-" + (oldTime.getDate() < 10 ? "0"+oldTime.getDate() : oldTime.getDate());
    return {
      start: startDate,
      end: endDate
    };  
}

// 工具函数: 将时间戳转换为 yyyy-mm-dd
export const FormatDate = (dateTime) =>{
    var date = new Date(dateTime);
    var YY = date.getFullYear();
    var MM = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hh = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var mm = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return YY + '-' + MM + '-' + DD;
}

// 工具函数: 获取url携带的参数[]
export const GetRequest = (value) => {
    var url = decodeURI(window.location.href); //?id="123456"&name="www";
    var object = {};
    if (url.indexOf("?") != -1) {  //url中存在问号，也就说有参数。
      var str = url.substr(url.indexOf("?") + 1);     //得到?后面的字符串
      var strs = str.split("&");   //将得到的参数分隔成数组[id="123456",name="www"];
      for (var i = 0; i < strs.length; i++) {
        object[strs[i].split("=")[0]] = strs[i].split("=")[1];//得到{id:'123456',name:'www'}
      }
    }
    return object[value];
}

// 工具函数: 获取url携带的参数
export  function getUrlKey(name){
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

// 工具函数：判断是否是URL
export  function isURL(url) {
    var pattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
    return pattern.test(url);
}

// 工具函数：身份证号码校验
export function VerfyCertificat(idCard) {
    //15位和18位身份证号码的正则表达式
    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if (regIdCard.test(idCard)) {
        if (idCard.length == 18) {
            var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
            var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
            var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
            for (var i = 0; i < 17; i++) {
                idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
            }
            var idCardMod = idCardWiSum % 11;//计算出校验码所在数组的位置
            var idCardLast = idCard.substring(17);//得到最后一位身份证号码
            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if (idCardMod == 2) {
                if (idCardLast == "X" || idCardLast == "x") {
                    return true;
                } else {
                    return false;
                }
            } else {
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if (idCardLast == idCardY[idCardMod]) {
                    return true;
                } else {
                    return false;
                }
            }
        }else{
            var test=/^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/
            if(test.test(idCard)){
                return true
            }else{
                return false
            }
        }
    } else if(idCard.length == 16){
        //老版本身份证 16 位校验
        var test=/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$/;
        if(test.test(idCard)){
            return true
        }else{
            return false
        }
    }else{
        return false;
    }
}

//根据出生日期计算年
function getYearAgeByBrithday(param){
    var result = param.intEndYear - param.intBeginYear;
    var allYear=0;
    if(param.intBeginMonth>param.intEndMonth){

        allYear=param.intEndYear - param.intBeginYear-1

    } else if (param.intBeginMonth == param.intEndMonth) {
        if (param.intBeginDate > param.intEndDate) {
            allYear=param.intEndYear - param.intBeginYear-1
        } else {
            allYear=param.intEndYear - param.intBeginYear
        }
    } else {
        allYear=param.intEndYear - param.intBeginYear
    }
    return allYear;
}

//根据出生日期计算月
function getMonthAgeByBrithday(param){
    debugger;
    var result = param.intEndYear - param.intBeginYear;
    var allMonth=0;
    if(param.intBeginDate>=param.intEndDate){
        if(result == 0){
            allMonth=param.intEndMonth-param.intBeginMonth;

        }else {
            if(param.intBeginDate>param.intEndDate){  //跨年
                allMonth=(12-param.intBeginMonth)+param.intEndMonth-1;
            }else if(param.intBeginDate<=param.intEndDate){
                allMonth=(12-param.intBeginMonth)+param.intEndMonth;
            }
        }


    } else {
        if(result == 0){
            allMonth = param.intEndMonth - param.intBeginMonth;
        }else{  //跨年
            allMonth = (12 - param.intBeginMonth) + param.intEndMonth;
        }
    }
    return allMonth;
}

//根据出生日期计算天数
function  getdataAgeByBrithday(param){
    debugger;
    var Feb;
    var isleap = isLeapYear(param.intBeginYear);
    if(isleap){
        Feb = 29;
    }else{
        Feb = 28;
    }
    var bigArr = [1,3,5,7,8,10,12];
    var smallArr = [4,6,9,11];
    param.bigArr =bigArr;
    param.smallArr =smallArr;
    param.Feb =Feb;
    var daycount=0;
    var result = param.intEndYear - param.intBeginYear;
    if(result == 0){
        for(var i=param.intBeginMonth ;i<=param.intEndMonth;i++){
            if (i == param.intEndMonth) {
                daycount += param.intEndDate-param.intBeginDate+1;
            } else {
                if($.inArray(i,bigArr)>=0){      //
                    daycount += 31;
                }else if($.inArray(i,smallArr)>=0){
                    daycount += 30;
                }else{
                    daycount += Feb;
                }
            }

        }
    } else {  //跨年
        for(var i=param.intBeginMonth;i<=12;i++){
            if($.inArray(i,bigArr)>=0){      //
                daycount += 31;
            }else if($.inArray(i,smallArr)>=0){
                daycount += 30;
            }else{
                daycount += Feb;
            }
            if(i==param.intBeginMonth){
                daycount = daycount -param.intBeginDate+1;
            }
        }
        for(var k=1 ;k<= param.intEndMonth;k++){

            if(k== param.intEndMonth){
                daycount +=param.intEndDate;
            }else{
                if($.inArray(k,bigArr)>=0){      //
                    daycount += 31;
                }else if($.inArray(k,smallArr)>=0){
                    daycount += 30;
                }else{
                    daycount += Feb;
                }
            }
        }
    }
    return daycount;
}

/**
 * 计算平年闰年
 */
function isLeapYear(year) {
    var cond1 = year % 4 == 0;  //条件1：年份必须要能被4整除
    var cond2 = year % 100 != 0;  //条件2：年份不能是整百数
    var cond3 = year % 400 ==0;  //条件3：年份是400的倍数
    //当条件1和条件2同时成立时，就肯定是闰年，所以条件1和条件2之间为“与”的关系。
    //如果条件1和条件2不能同时成立，但如果条件3能成立，则仍然是闰年。所以条件3与前2项为“或”的关系。
    //所以得出判断闰年的表达式：
    var cond = cond1 && cond2 || cond3;
    if(cond) {
        return true;
    } else {
        return false;
    }
}



// 工具函数：根据身份证号码获取[出生日期][年龄][性别]
export function GetInfoByIdCardFn(idCard) {
    let num = idCard;

    let baseInformation = {
        birthday: "",
        age: "",
        sex: "",
        sexUnit: "Y",
    };

    let birthdayNum = "";
    let sexNum = "";
    if (num.length == 18) {
        birthdayNum = num.substring(6, 14);
        sexNum  = parseInt(num.substring(16,17));
    } else if(num.length == 15){
        birthdayNum = "19" + num.substring(6, 12);
        sexNum  = parseInt(num.substring(14,15));
    }

    // 性别
    if(sexNum % 2 == 0){
        baseInformation['sex'] = 2;
    }else{
        baseInformation['sex'] = 1;
    }

    // 出生年月
    let birthDayDate = new Date(birthdayNum.replace(/^(\d{4})(\d{1}|\d{2})(\d{1}|\d{2})$/, "$1-$2-$3"));
    baseInformation['birthday'] = birthDayDate;

    //年龄
    let intBeginYear = parseInt(birthDayDate.substring(0, 4));  // 获取出生日期 年份
    let intBeginMonth = parseInt(birthDayDate.substring(birthDayDate.indexOf("-") + 1, birthDayDate.indexOf("-") + 3),10); // 获取出生日期 月份
    let intBeginDate = parseInt(birthDayDate.substring(birthDayDate.lastIndexOf("-") + 1, birthDayDate.lastIndexOf("-") + 3),10); // 获取出生日期 日

    let nowDate = new Date().Format("yyyy-MM-dd hh:mm:ss");
    let intEndYear = parseInt(nowDate.substring(0, 4));
    let intEndMonth = parseInt(nowDate.substring(nowDate.indexOf("-") + 1, nowDate.indexOf("-") + 3),10);
    let intEndDate = parseInt(nowDate.substring(nowDate.lastIndexOf("-") + 1, nowDate.lastIndexOf("-") + 3),10);

    var temp = (intEndYear - intBeginYear) * 12 - intBeginMonth + intEndMonth;
    if (param.intBeginMonth == param.intEndMonth) {
        if (param.intBeginDate > param.intEndDate) {
            temp = temp - 1;
        }
    }
    if((intEndYear - intBeginYear < 2)&& temp < 12 && temp > 3 ){  //年相减小于2 并且 月数小于12  ---   月
        $("#"+dwid).val("M");
        var allMonth = getMonthAgeByBrithday(param);
        $("#" + param.ageid).val(allMonth);

    }else if(intEndYear - intBeginYear>0&& temp>=12){   //年
        $("#"+dwid).val("Y");
        var allYear = getYearAgeByBrithday(param);
        $("#" + param.ageid).val(allYear);

    }else if((intEndYear - intBeginYear < 2)&& temp<=3 ){  //天
        $("#"+dwid).val("D");
        var daycount = getdataAgeByBrithday(param);
        $("#" + param.ageid).val(daycount);

    }

    return baseInformation;
}